package ping 
{
	
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.events.Event;
	import RequestSender;
	/**
	 * ...
	 * @author yaempechenki@gmail.com
	 */
	public class PingHelper extends EventDispatcher
	{
		public static const VK:String = "hello_durov";
		public static const JENKINS:String = "hello_jenkins";
		
		private var pingTimer:Timer = null;
		private var sendRequest:RequestSender = null;
		private var pingMe:IPing = null;
		
		public function PingHelper(type:String="") {
			pingMe = pingerFabrique(type);
			
			if (sendRequest)
			{
				sendRequest.destroy();
				sendRequest = null;
			}
			sendRequest =  new RequestSender();
			sendRequest.onComplete = onResponce;
			
			pingTimer = new Timer(Settings.PING_TIME);
			pingTimer.addEventListener(TimerEvent.TIMER, pingTimerHandler);
			pingTimer.start();
		}
		
		
		
		private function pingTimerHandler(event:TimerEvent):void {
			sendRequest.load(pingMe.URL);
		}
		
		private function onResponce(response:String):void {
			if (pingMe.ping(response)) {
				dispatchEvent(new Event(AppEvent.APP_COMMAND_ON));
			} else {
				dispatchEvent(new Event(AppEvent.APP_COMMAND_OFF));
			}
		}
		
		private function pingerFabrique(type:String):IPing {
			if (type == VK) {
				return new PingVK();
			}
			return new PingJenkins();
		}
	}
}